package edu.ustb.controller.goods;

import com.alibaba.fastjson.JSONObject;
import edu.ustb.domain.goods.Goods;
import edu.ustb.service.goods.GoodsListService;
import edu.ustb.service.goods.Impl.GoodsListServiceImpl;
import edu.ustb.view.JsonData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "GoodsDetailServlet", value = "/WebContent/goods/goodsDetails")
public class GoodsDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置解码方式
        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        // 获取从前端传到后端的需要查询详情的商品 Id
        String goodsId = request.getParameter("goodsId");
        PrintWriter out = response.getWriter();

        if (goodsId == null){
            goodsId = "1";
        }

        System.out.println("在此处获得的商品的Id: "+goodsId);
        try{
            // 定义 Goods 的服务层
            GoodsListService goodsListService = new GoodsListServiceImpl();
            // 通过 Goods 的服务层获取所要展示详情的商品
            Goods goods = goodsListService.getGoodsDetailsByGoodsId(Integer.parseInt(goodsId));

            // 在服务器终端打印所查询到的 Goods
            System.out.println(goods);

            // 将查询的数据转化为 Json 数据
            JsonData result = JsonData.success("本次商品查询成功！", goods);

            // 在终端打印数据的 Json 字符串
            System.out.println(JSONObject.toJSONString(result));

            // 在对应的 goodsDetails 服务器网页上打印 Json 字符串
            out.write(JSONObject.toJSONString(result));
            out.flush();
            out.close();

        }catch(Exception e)
        {
            // 若遇到错误，则执行下述代码
            e.printStackTrace();
            JsonData result  = JsonData.fail("程序出现异常！");
            out.write(JSONObject.toJSONString(result));
            out.flush();
            out.close();
        }
    }
}
